package com.emasdemo.util;

import android.content.Context;
import android.util.Log;

import com.alibaba.sdk.android.httpdns.HttpDns;
import com.alibaba.sdk.android.httpdns.HttpDnsService;
import com.emasdemo.bean.IpEvent;
import com.emasdemo.application.SophixStubApplication;

import org.greenrobot.eventbus.EventBus;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import okhttp3.Dns;

public class OkHttpDns implements Dns {
    private static final Dns SYSTEM = Dns.SYSTEM;
    HttpDnsService httpdns;//httpdns 解析服务
    private static OkHttpDns instance = null;

    private OkHttpDns(Context context) {
        Log.i("OkHttpDns", SophixStubApplication.httpdns_accountId + "    " + SophixStubApplication.httpdns_secretKey);
        httpdns = HttpDns.getService(context, SophixStubApplication.httpdns_accountId, SophixStubApplication.httpdns_secretKey);
        httpdns.setPreResolveAfterNetworkChanged(true);
        httpdns.setLogEnabled(true);//设置是否httpdns输出日志
        httpdns.setExpiredIPEnabled(true);// 允许过期IP以实现懒加载策略
        httpdns.setCachedIPEnabled(true);//允许持久化缓存
        httpdns.enableIPv6(true);//开启ipv6功能
    }

    public static OkHttpDns getInstance(Context context) {
        if (instance == null) {
            instance = new OkHttpDns(context);
        }
        return instance;
    }

    @Override
    public List<InetAddress> lookup(String hostname) throws UnknownHostException {
        Log.i("OkHttpDns", "原hostname：" + hostname);
        //通过异步解析接口获取ip
        String ip = httpdns.getIpByHostAsync(hostname);
        if (ip != null) {
            //如果ip不为null，直接使用该ip进行网络请求
            List<InetAddress> inetAddresses = Arrays.asList(InetAddress.getAllByName(ip));
            Log.i("OkHttpDns", "Get IP:" + inetAddresses + "   sessionId:" + httpdns.getSessionId());
            String[] ips = httpdns.getIpsByHostAsync(hostname);
            ArrayList<String> list = new ArrayList<>();
            for (int i = 0; i < ips.length; i++) {
                list.add(ips[i]);
            }
            Log.i("OkHttpDns", "Get IPs: " + list.toString() + "   sessionId:" + httpdns.getSessionId());

            EventBus.getDefault().post(new IpEvent("Get IP: " + ip + " for host: " + hostname + " from HTTPDNS successfully!"));
            return inetAddresses;
        }

        //如果返回null，走系统DNS服务解析域名
        return Dns.SYSTEM.lookup(hostname);
    }
}
